#!/bin/bash
document_root=/data/www/public_html/beta.thethao.vnexpress.net/server/Job
worker=sync-cache.sh
prog=sync-cached.sh
num_prog=1
date=`date +"%Y-%m-%d"`
log_file=$document_root/logs/sync-cache-$date.log
# gearman key
gearman_func=vnett_sync_cache
#Start process
start() {
	echo "Starting $prog"
	/bin/bash $document_root/$worker >> $log_file 2>&1 &
}

# Stop all process
stop() {
	echo "Stopping $prog"
	ps -ef | grep "$worker" | grep -v grep | awk '{print$2}' | xargs kill -9
	ps -ef | grep "$gearman_func" | grep -v grep | awk '{print$2}' | xargs kill -9
}
# Detect process
detect() {
	current_num_prog=`ps -ef | grep -v grep | grep -c "$worker"`
	if [ "$current_num_prog" -lt "$num_prog" ]; then
		let new_prog=$num_prog-$current_num_prog
		i=1
		while [ $i -le $new_prog ]; do
			start
			let i++
		done
	fi
}
# Renew cache
renew() {
	input="
	s:117:"add:vnett:http://beta.thethao.vnexpress.net:vnett:/data/www/public_html/beta.thethao.vnexpress.net/public/index.html";"
	/build/gearmand/bin/gearman -h 180.148.142.86 -p 4730 -b -f vnett_sync_cache $input
	echo "Renewed"
}
case "$1" in
	"start" )
           start
           ;;
	"stop" )
	   stop
           ;;
	"restart" )
	   stop
	   detect
           ;;
	"detect" )
           detect
           ;;
	"renew" )
           renew
           ;;
     	* )
           echo "Usage: $prog {start|stop|restart|detect|renew)"
           exit 1
esac
usleep 500
ps -ef | grep -v grep | grep "$worker"
exit 0
